/**
 * 存储 - 用户模块
 */
import { getUserStorageKey } from '@/src/config.js'

const STORAGE_KEY = getUserStorageKey()

export default {
	state: {
		Id: 0,
		LoginName: '',
		UserName: '',
		Token: '',
		hasLogged: false,
	},
	getters: {
		// 判断是否已登录
		isLogin: (state) => {
			return !!state.Token
		},
		// 是否已完成登录（登录成功并跳转到聊天首页）
		hasLogged: (state) => {
			return !!state.Token && !!state.hasLogged
		},
	},
	mutations: {
		// 设置用户信息
		getUserInfo(state, data) {
			if (!data) {
				data = uni.getStorageSync(STORAGE_KEY)
			}
			state.Id = data.Id || state.Id
			state.LoginName = data.LoginName || state.LoginName
			state.UserName = data.UserName || state.UserName
			state.Token = data.Token || state.Token
		},
		// 保存用户信息
		setUserInfo(state) {
			uni.setStorageSync(STORAGE_KEY, {
				Id: state.Id,
				LoginName: state.LoginName,
				UserName: state.UserName,
				Token: state.Token,
			})
		},
		// 完成登录
		getHasLogged(state) {
			state.hasLogged = true
		},
		// 清除数据（登出）
		clearUserInfo(state) {
			if (state) {
				state.Id = 0
				state.LoginName = ''
				state.UserName = ''
				state.Token = ''
			}
			uni.removeStorageSync(STORAGE_KEY)
			state.hasLogged = false
		},
	},
	actions: {
		// 初始化用户信息
		initUserInfo({ commit }) {
			commit('getUserInfo')
		},
		// 设置完成登录状态
		setHasLogged({ commit }) {
			commit('getHasLogged', true)
		},
		// 写入用户token
		writeUserToken({ commit }, token) {
			commit('getUserInfo', { Token: token })
			commit('setUserInfo')
		},
		// 写入 & 更新用户信息
		saveUserInfo: function ({ commit, state }, userApiData) {
			commit('getUserInfo', userApiData)
			commit('setUserInfo')
		},
		// 设置服务器时间（刷新）
		setServerDate({ commit }, value) {
			commit('getServerDate', value)
		},
		// 方法：获取登录信息（含检测）
		getLoginInfo: async function ({ commit, getters, state }, redirect = true) {
			return await new Promise(async (resolve, reject) => {
				if (!getters.isLogin) {
					// 防止数据意外丢失
					commit('getUserInfo')
				}
				if (!getters.isLogin) {
					// 未登录时
					commit('clearUserInfo')
					if (redirect) {
						uni.reLaunch({
							url: '/pages/login/login',
						})
					}
					reject()
				} else {
					resolve({
						Id: state.Id,
						LoginName: state.LoginName,
						UserName: state.UserName,
						Token: state.Token,
					})
				}
			})
		},
		// 方法：用户登出
		userLogout({ commit }) {
			commit('clearUserInfo')
		},
	},
}
